<template>
  <div class="address-container">
    <van-nav-bar title="常用地址" left-text="" left-arrow @click-left="goBack"/>
    <div v-for="(address, index) in addresses" :key="index" class="address-item"
         :class="{'default-address': index === defaultAddressIndex}">
      <div class="address-header">
        <span>{{ address.contactName }}</span>
        <span>{{ address.contactPhone }}</span>
        <span>{{ address.addressName }}</span>
        <button @click="deleteAddress(address.addressId)">删除</button>
      </div>
      <div class="address-content">
        <p>{{ address.detailAddress }}</p>
      </div>
      <div class="address-footer">
        <label>
          <input type="radio" v-model="defaultAddressIndex" @change="setDefaultAddress(index)" :value="index"/>
          设为默认
        </label>
      </div>
    </div>
    <button @click="addNewAddress">新增服务地址</button>
  </div>
</template>

<script>
import axios from "axios";
import { Dialog, Toast } from 'vant';

export default {
  data() {
    return {
      addresses: [],
      defaultAddressIndex: null,
      user: {},
    };
  },
  methods: {
    deleteAddress(id) {
      Dialog.confirm({
        title: '确认删除',
        message: '确定要删除该地址吗？',
      })
          .then(() => {
            axios.delete(`http://localhost:10086/api/admin/address/remove/${id}`).then(res => {
              console.log('删除成功', res.data);
              this.getAddress();
              this.getDefaultAddress();
              Toast.success('删除成功');
            }).catch(error => {
              console.error('删除失败', error);
            });
          })
          .catch(() => {
            console.log('取消删除');
          });
    },

    addNewAddress() {
      this.$router.push('/selectServiceType');
    },

    getAddress() {
      axios.get(`http://localhost:10086/api/admin/address/${this.user.id}`).then(res => {
        this.addresses = res.data.data;
        console.log(res.data);
        this.getDefaultAddress(); // 确保在获取地址后获取默认地址
      });
    },

    getDefaultAddress() {
      axios.get(`http://localhost:10086/api/admin/address/defeaul/${this.user.id}`).then(res => {
        if (res.data.data && res.data.data.addressId !== undefined) {
          const defaultAddressId = res.data.data.addressId;
          this.defaultAddressIndex = this.addresses.findIndex(addr => addr.addressId === defaultAddressId);
          sessionStorage.setItem("address", JSON.stringify(res.data.data));
        } else {
          console.log('没有默认地址');
          this.defaultAddressIndex = null;
        }
      }).catch(error => {
        console.error('获取默认地址失败', error);
      });
    },

    setDefaultAddress(index) {
      const addressId = this.addresses[index].addressId;
      axios.get(`http://localhost:10086/api/admin/address/updatedefault/${this.user.id}/${addressId}`).then(res => {
        console.log('默认地址更新成功', res.data);
        this.getDefaultAddress();
      }).catch(error => {
        console.error('更新默认地址失败', error);
        this.defaultAddressIndex = this.addresses.findIndex(addr => addr.is_default);
      });
      this.$router.push('/yuyue')
    },

    goBack() {
      this.$router.go(-1);
    },
  },
  created() {
    const userStr = sessionStorage.getItem("userDB");
    if (userStr) {
      try {
        this.user = JSON.parse(userStr);
        this.getAddress();
      } catch (error) {
        console.error("解析用户数据失败:", error);
      }
    } else {
      console.log("没有找到用户数据");
    }
  }
};
</script>

<style scoped>
.address-container {
  padding: 20px;
}

.address-item {
  border: 1px solid #ccc;
  margin-bottom: 20px;
  padding: 10px;
  border-radius: 5px;
}

.address-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.address-content {
  margin-top: 10px;
}

.address-footer {
  margin-top: 10px;
  display: flex;
  align-items: center;
}

button {
  margin-left: 10px;
}

.default-address {
  border-color: #42b983; /* 高亮默认地址 */
}
</style>
